<?php

namespace app\office\controller;


use PhpOffice\PhpWord\Exception\CopyFileException;
use PhpOffice\PhpWord\Exception\CreateTemporaryFileException;
use PhpOffice\PhpWord\TemplateProcessor;

/**
 * 这是一个word操作类
 */
class Word
{

    public $rootPath;

    public function __construct()
    {
        $this->rootPath=env('root_path');
    }

    /**
     * 替换word中对应的文档内容
     * @param $filePath string 文件路径
     * @param $data array 替换内容
     * @throws CopyFileException
     * @throws CreateTemporaryFileException
     */
    public function substitute($filePath,$data){

        $this->rootPath= env('root_path');

        $tmp=new TemplateProcessor($this->rootPath.$filePath);

        foreach ($data as $key=>$datum){
            $tmp->setValue($key,$datum);
        }
        $fileName=GetRandStr(32).".docx";
        $tmp->saveAs($this->rootPath."public/words/files/".$fileName);

        //返回文件名
        return $fileName;
    }

    /**
     * 将文件返回到页面进行下载
     * @param $filePath string 文件路径
     * @param $fileName string 返回的文件名
     */
    public function download(string $filePath, string $fileName){
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="'.$fileName.'"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: '.filesize($this->rootPath.$filePath));
        readfile($this->rootPath.$filePath);
    }
}